<template>
  <el-dialog v-model="visible" title="选择动态" width="80%" :before-close="handleClose">
    <!-- 搜索栏 -->
    <div class="handle-box">
      <el-input v-model="searchForm.authorId" placeholder="作者ID" class="handle-input mr10 mb10" clearable />
      <el-input v-model="searchForm.authorName" placeholder="作者名字" class="handle-input mr10 mb10" clearable />
      <el-input v-model="searchForm.noteTitle" placeholder="笔记标题" class="handle-input mr10" clearable />
      <el-input v-model="searchForm.ipRealAddress" placeholder="IP真实地址" class="handle-input mr10" clearable />
      <el-select v-model="searchForm.noteCategory" placeholder="类型" class="handle-input mr10" clearable>
        <el-option label="普通发布" :value="0" />
        <el-option label="宠物日记" :value="1" />
        <el-option label="热点" :value="2" />
      </el-select>
      <!-- <el-date-picker v-model="searchForm.publishTime" type="datetimerange" range-separator="至"
        start-placeholder="开始时间" end-placeholder="结束时间" class="mr10" /> -->
      <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border class="table" ref="momentTable" header-cell-class-name="table-header"
      @row-click="handleRowClick" row-key="id">
      <el-table-column type="radio" width="55">
        <template #default="scope">
          <el-radio v-model="selectedMoment" :label="scope.row.id"
            @change="handleRadioChange(scope.row)">&nbsp;</el-radio>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="动态ID" width="100" />
      <el-table-column prop="publisherAvatar" label="发布者头像" width="100" align="center">
        <template #default="scope">
          <el-image v-if="scope.row.publisherAvatar" :src="scope.row.publisherAvatar"
            style="width:40px;height:40px;border-radius:50%;" fit="cover" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="publisherName" label="发布者" min-width="150">
        <template #default="scope">
          {{ scope.row.publisherName || scope.row.publisherId || '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="firstPicture" label="首图" width="100" align="center">
        <template #default="scope">
          <el-image v-if="scope.row.firstPicture" :src="scope.row.firstPicture"
            style="width:60px;height:60px;border-radius:4px;" fit="cover"
            :preview-src-list="[scope.row.firstPicture]" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="mediaList" label="图片/视频" width="100" align="center">
        <template #default="scope">
          <span v-if="scope.row.noteType === 3 || !scope.row.mediaList || scope.row.mediaList.length === 0">-</span>
          <el-button v-else type="primary" size="mini" @click="openMediaDialog(scope.row.mediaList)">
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" min-width="200">
        <template #default="scope">
          <span>{{ scope.row.title || '无标题' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="内容" min-width="250">
        <template #default="scope">
          <div class="content-cell">
            {{ scope.row.content || '无内容' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="publishTime" label="发布时间" width="160">
        <template #default="scope">
          {{ dateFormat(scope.row.publishTime) }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pagination.currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="pagination.total" />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selected-info">{{ selectedMomentData ? `已选择：${selectedMomentData.title || '无标题'}` : '未选择动态'
          }}</span>
        <div>
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleConfirm">确定</el-button>
        </div>
      </div>
    </template>

    <!-- 媒体预览弹窗 -->
    <el-dialog v-model="mediaDialog.visible" width="40%" title="媒体预览" append-to-body>
      <div style="display: flex; justify-content: center;">
        <media-view v-if="mediaDialog.list.length" :list="mediaDialog.list" />
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import moment from "moment";
import MediaView from "@/components/mediaVIew.vue";
import { getMoments } from "@/api/content";

export default {
  name: "SelectMoments",
  components: {
    MediaView
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    // 已选中的动态数据
    selectedData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:modelValue', 'confirm'],
  data() {
    return {
      searchForm: {
        authorId: "",
        authorName: "",
        noteTitle: "",
        ipRealAddress: "",
        noteCategory: "",
        publishTime: [],
      },
      tableData: [],
      selectedMoment: null, // 当前选中的动态ID
      selectedMomentData: null, // 当前选中的动态完整数据
      // 分页相关
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      mediaDialog: {
        visible: false,
        list: [],
      }
    };
  },
  computed: {
    visible: {
      get() {
        return this.modelValue;
      },
      set(val) {
        this.$emit('update:modelValue', val);
      }
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.getData();
        this.initSelectedData();
      }
    }
  },
  methods: {
    dateFormat(val) {
      return val ? moment(val).format("YYYY-MM-DD HH:mm:ss") : "";
    },
    formatDateTime(date) {
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },

    handleSearch() {
      // 搜索时重置到第一页
      this.pagination.currentPage = 1;
      this.getData();
    },
    // 分页相关方法
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getData();
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getData();
    },
    buildSearchParams() {
      const params = {
        // 必须的分页参数
        limit: this.pagination.pageSize,
        offset: this.pagination.currentPage
      };

      // 根据搜索表单构建查询参数
      if (this.searchForm.authorId) {
        params.authorId = this.searchForm.authorId;
      }
      if (this.searchForm.authorName) {
        params.authorName = this.searchForm.authorName;
      }
      if (this.searchForm.noteTitle) {
        params.noteTitle = this.searchForm.noteTitle;
      }
      if (this.searchForm.ipRealAddress) {
        params.ipRealAddress = this.searchForm.ipRealAddress;
      }
      if (this.searchForm.noteCategory !== "" && this.searchForm.noteCategory !== null) {
        params.noteCategory = this.searchForm.noteCategory;
      }
      if (this.searchForm.publishTime && this.searchForm.publishTime.length === 2) {
        params.startTime = this.searchForm.publishTime[0];
        params.endTime = this.searchForm.publishTime[1];
      }

      return params;
    },
    buildMediaList(item) {
      const mediaList = [];

      // 根据noteType处理不同类型的媒体，排除首图
      switch (item.noteType) {
        case 1: // 图文类型 - 只获取imgList字段
          if (item.imgList && item.imgList.length > 0) {
            item.imgList.forEach(img => {
              // 排除首图
              if (img !== item.firstPicture) {
                mediaList.push({
                  type: 'image',
                  url: img
                });
              }
            });
          }
          break;

        case 2: // 视频类型 - 只获取videoUrl字段
          if (item.videoUrl) {
            mediaList.push({
              type: 'video',
              url: item.videoUrl
            });
          }
          break;

        case 3: // 文字类型 - 不处理任何媒体
          break;
      }

      return mediaList;
    },
    async getData() {
      try {
        const params = this.buildSearchParams();
        const response = await getMoments(params);

        if (response && response.data) {
          // 将API返回的数据映射到表格需要的格式
          this.tableData = response.data.rows.map(item => ({
            id: item.noteId || item.id,
            city: item.ipRealAddress || '未知',
            publisherAvatar: item.authorAvatar || item.avatarUrl || '',
            publisherName: item.authorName || '',
            publisherId: item.authorId || '',
            noteType: item.noteType,
            firstPicture: item.firstPicture,
            mediaList: this.buildMediaList(item),
            title: item.noteTitle,
            content: item.noteContent,
            topic: item.noteLabel,
            topicsList: item.topicsList || [], // 话题列表数据
            publishTime: item.createTime,
            // 保留原始数据用于编辑
            _original: item
          }));

          // 更新总数（如果接口返回了总数）
          if (response.data.total !== undefined) {
            this.pagination.total = response.data.total;
          }
        }
      } catch (error) {
        console.error('获取动态数据失败:', error);
        this.$message.error('获取动态数据失败');
      }
    },
    openMediaDialog(list) {
      this.mediaDialog.list = list || [];
      this.mediaDialog.visible = true;
    },
    // 初始化已选中的数据
    initSelectedData() {
      if (this.selectedData) {
        this.selectedMoment = this.selectedData.id;
        this.selectedMomentData = { ...this.selectedData };
      } else {
        this.selectedMoment = null;
        this.selectedMomentData = null;
      }
    },
    // 处理单选变化
    handleRadioChange(row) {
      this.selectedMomentData = { ...row };
    },
    // 处理行点击
    handleRowClick(row) {
      this.selectedMoment = row.id;
      this.selectedMomentData = { ...row };
    },
    // 关闭弹窗
    handleClose() {
      this.visible = false;
    },
    // 确认选择
    handleConfirm() {
      this.$emit('confirm', this.selectedMomentData);
      this.handleClose();
    },
  },
};
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>
<style lang='scss' scoped>
.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.table {
  width: 100%;
  font-size: 14px;
}

.red {
  color: #ff0000;
}

.green {
  color: #0ab618;
}

.mr10 {
  margin-right: 10px;
}

.table-td-thumb {
  display: block;
  margin: auto;
  height: 60px;
  width: 60px;
}

.crop-demo {
  display: flex;
  align-items: flex-end;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 148px;
  height: 148px;

  .pre-img {
    width: 146px;
    height: 146px;
    background: #f8f8f8;
    border: 1px solid #eee;
    border-radius: 5px;
    object-fit: cover;
  }

  .crop-input {
    position: absolute;
    width: 148px;
    height: 148px;
    left: 0px;
    top: 0px;
    opacity: 0;
    cursor: pointer;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
}

.picPreview {
  width: 100%;
}

.mb10 {
  margin-bottom: 10px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.content-cell {
  max-height: 60px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  line-height: 20px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-left: 10px;
}

::v-deep .el-date-editor {
  margin-right: 10px;
  width: 300px;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.selected-info {
  color: #606266;
  font-size: 14px;
}

.topic-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}
</style>
